<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderAddress;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LogisticsController extends BaseController
{

    public $logis_code = array(
        array("company" => "顺丰速运", "company_code" => 'shunfeng'),
        array("company" => "京东物流", "company_code" => 'jd'),
        array("company" => "圆通速递", "company_code" => 'yuantong'),
        array("company" => "申通快递", "company_code" => 'shentong'),
        array("company" => "极兔速递", "company_code" => 'jtexpress'),
        array("company" => "中通快递", "company_code" => 'zhongtong'),
        array("company" => "韵达快递", "company_code" => 'yunda'),
        array("company" => "邮政快递包裹", "company_code" => 'youzhengguonei'),
        array("company" => "EMS", "company_code" => 'ems'),
        array("company" => "德邦快递", "company_code" => 'debangkuaidi'),
        array("company" => "菜鸟速递", "company_code" => 'danniao'),
        array("company" => "德邦", "company_code" => 'debangwuliu'),
    );

    /**
     * @return \Illuminate\Http\JsonResponse
     * 物流公司编码
     */
    public function getLogisticsCode()
    {
        $code = $this->logis_code;
        return $this->ResultJson(1, '获取成功!', $code);
    }

    /**
     * @param $res
     * @param $order_id
     * @return mixed
     * 设置发货地址
     */
    public function getSendAddress($res, $order_id)
    {
        sort($res);
        foreach ($res as $k => $v) {
            if ($v['status'] == "揽收") {
                $address = str_replace(',', "", $v['areaName']);
                (new Order())->where([['id', '=', $order_id]])->update(['send_address' => $address]);
                return $address;
            }
            continue;
        }
    }
    
    
    /***
     * 查询物流信息
     */

    public function getLogisticsInfo(Request $request)
    {

        $pra = $request->input();
        if (empty($pra['order_id'])) {
            return $this->ResultJson(0, '订单号不能为空!', []);
        }
        $orderInfo = (new Order())->where([['id', '=', $pra['order_id']]])->first();
        if ($orderInfo->delivery_status != 1) {
            return $this->ResultJson(0, '该订单还没有发货,不能查询物流!', []);
        }
        if (empty($orderInfo->logis_code) || empty($orderInfo->logis_num)) {
            return $this->ResultJson(0, '该订单还没有物流单号,不能查询物流!', []);
        }
        $res = $this->getLogis($orderInfo->logis_code, $orderInfo->logis_num, $url = 'https://poll.kuaidi100.com/poll/query.do');
        if (!empty($res['data'])) {
            if (empty($orderInfo->send_address)) {
                $this->getSendAddress($res['data'], $pra['order_id']);
            }
            return $this->ResultJson(1, '获取成功!', $res['data']);
        }
        return $this->ResultJson(0, '获取成功!', $res);
    }





    /**
     * @param $post_data
     * @param $url
     * @return mixed
     * 地图轨迹
     */
    public function getMapQuery(Request $request)
    {
        $pra = $request->input();
        if(empty($pra['order_id'])){
            return $this->ResultJson(0, '订单号不能为空!', []);
        }
        $orderInfo = (new Order())->where([['id','=',$pra['order_id']]])->first();
        if($orderInfo->delivery_status !=1){
            return $this->ResultJson(0, '该订单还没有发货,不能查询物流!', []);
        }
        if(empty($orderInfo->logis_code) || empty($orderInfo->logis_num)){
            return $this->ResultJson(0, '该订单还没有物流单号,不能查询物流!', []);
        }
        //获取发货地址
        if(empty($orderInfo->send_address)){
            $res = $this->getLogis($orderInfo->logis_code, $orderInfo->logis_num, $url = 'https://poll.kuaidi100.com/poll/query.do');
            if (!empty($res['data'])) {
                if (empty($orderInfo->send_address)) {
                    $address =  $this->getSendAddress($res['data'], $pra['order_id']);
                }
            }
        }else{
            $address = $orderInfo->send_address;
        }
        //获取收货地址
        $to_address = $this->getToAddress($pra['order_id']);
        $key = env('LOGIS_KEY');               // 客户授权key
        $customer = env('LOGIS_CUSTOMER');                 // 查询公司编号
        $param = array (
            'com' => $orderInfo->logis_code,             // 快递公司编码
            'num' =>$orderInfo->logis_num,     // 快递单号
            'phone' => '',                // 手机号
            'from' => $address,                 // 出发地信息
            'to' => $to_address,                   // 目的地信息
            'resultv2' => '5',            // 添加此字段表示开通行政区域解析功能
            'show' => '0',                // 返回格式：0：json格式（默认），1：xml，2：html，3：text
            'order' => 'desc',            // 返回结果排序:desc降序（默认）,asc 升序
            'orderTime' => ''             // 订单下单时间，格式为（yyyy-MM-dd HH:mm:ss）如：2020-12-16 12:59:59
        );
        // 请求参数
        $post_data = array();
        $post_data['customer'] = $customer;
        $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $sign = md5($post_data['param'].$key.$post_data['customer']);
        $post_data['sign'] = strtoupper($sign);
        $url = 'https://poll.kuaidi100.com/poll/maptrack.do';    // 地图轨迹请求地址
        $res = $this->sendPost($post_data,$url);
        if(!empty($res['data'])){
            return $this->ResultJson(1, '获取成功!', $res);
        }
    }


    /**
     * @param $post_data
     * @param $url
     * @return mixed
     * 获取收货地址
     *
     */
    public function getToAddress($order_id)
    {
        $address_info = (new OrderAddress())->with(['province', 'city', 'district'])->where([['order_id', '=', $order_id]])->first();
        return $address_info->province->name . $address_info->city->name . $address_info->district->name;
    }

    /**
     * @param $post_data
     * @param $url
     * @return mixed
     * 发送POSt请求
     */
    public function sendPost($post_data, $url)
    {
        // 发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        // 第二个参数为true，表示格式化输出json
        $data = json_decode($result, true);
        return $data;
    }

    /**
     * @param $logis_code
     * @param $logis_num
     * @param $url
     * @return mixed
     * 查询物流信息
     */
    public function getLogis($logis_code, $logis_num,$url)
    {
        $key = env('LOGIS_KEY');               // 客户授权key
        $customer = env('LOGIS_CUSTOMER');                 // 查询公司编号
        $param = array(
            'com' => $logis_code,             // 快递公司编码
            'num' => $logis_num,     // 快递单号
            'phone' => '',                // 手机号
            'from' => '',                 // 出发地城市
            'to' => '',                   // 目的地城市
            'resultv2' => '1',            // 开启行政区域解析
            'show' => '0',                // 返回格式：0：json格式（默认），1：xml，2：html，3：text
            'order' => 'desc'             // 返回结果排序:desc降序（默认）,asc 升序
        );
        //请求参数
        $post_data = array();
        $post_data['customer'] = $customer;
        $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $sign = md5($post_data['param'] . $key . $post_data['customer']);
        $post_data['sign'] = strtoupper($sign);
        $res = $this->sendPost($post_data, $url);
        return $res;
    }

}
